//
//  BallView.m
//  rolling
//
//  Created by Mac on 10-7-11.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "BallView.h"
#import "GameAction.h"
#import "Ball.h"
#define PI 3.1415926536

@implementation BallView

@synthesize gameAction;
@synthesize acceleration;

//@synthesize ball;

- (id)initWithCoder:(NSCoder *)coder{
	if (self = [super initWithCoder:coder]) {
		self.gameAction = [[GameAction alloc] init];
		//self.ball = [[Ball alloc]init];
		
	}
	
	return self;
}

- (id)initWithFrame:(CGRect)frame{
	if (self = [super initWithFrame:frame]) {
	
	}
	return self;
}

- (void)drawRect:(CGRect)frame {
	[self.gameAction.person.image drawAtPoint:self.gameAction.person.location];
	for (Ball *tmpBall in self.gameAction.sysInfo.balls ) {
		[tmpBall.image drawAtPoint: tmpBall.location];
	}
	//[image drawAtPoint:currentPoint];
}



- (void) draw {
	static NSDate *lastDrawTime;
	
	if (lastDrawTime != nil) {
		
		//control by accelerometer
		int xRatio;
		int yRatio;
		//set accelerate ratio
		if ((self.gameAction.person.speedY*acceleration.y)<0) {
			yRatio = negRatio;
		}
		else {
			yRatio = posRatio;
		}
		if ((self.gameAction.person.speedX*acceleration.x)<0) {
			xRatio = posRatio;
		}
		else {
			xRatio = negRatio;
		}
		

		NSTimeInterval secondsSinceLastDraw = -([lastDrawTime timeIntervalSinceNow]);
		
		self.gameAction.person.speedY = self.gameAction.person.speedY - (acceleration.y * secondsSinceLastDraw);
		self.gameAction.person.speedX = self.gameAction.person.speedX + (acceleration.x * secondsSinceLastDraw);
		
		CGFloat xAcceleration = secondsSinceLastDraw * [[self.gameAction person] speedX] * xRatio;
		CGFloat yAcceleration = secondsSinceLastDraw * [[self.gameAction person] speedY] * yRatio;
		CGPoint location = [[self.gameAction person]location];
		
		self.gameAction.person.location = CGPointMake(location.x + xAcceleration, location.y + yAcceleration);
		[self.gameAction action];
		CGRect fresh = CGRectMake(0,0,360,480);
		[self setNeedsDisplayInRect: fresh];
	}
	[lastDrawTime release];
	lastDrawTime = [[NSDate alloc] init];
}
@end

